package com.keshan.controller.push;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.keshan.pojo.push.PushHistory;
import com.keshan.service.IPushHistoryService;
import com.keshan.utils.JWTUtils;
import com.keshan.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * 推送历史Controller
 *
 * @author TangZheng
 * @date 2022-12-03
 */
@CrossOrigin
@RestController
@RequestMapping("/pushHistory")
public class PushHistoryController {
    @Autowired
    private IPushHistoryService pushHistoryService;

    /**
     * 查询推送历史列表
     */
    @GetMapping("/list")
    public Msg list(PushHistory pushHistory, HttpServletRequest request) {
        try {
            String token = request.getHeader("token");
            DecodedJWT decodedJWT = JWTUtils.verifyAndInfo(token);
            String username = decodedJWT.getClaim("username").asString();
            pushHistory.setMdUserName(username);
            pushHistory.setTemplateDictType("push_template_type");
            List<PushHistory> list = pushHistoryService.selectPushHistoryList(pushHistory);
            if (list != null && list.size() > 0) {
                List<Long> idList = new ArrayList<>();
                for (PushHistory history : list) {
//                    查出来的未发送的标记为已发送
                    if (history.getStatus() == 0) {
                        idList.add(history.getId());
                    }
                }
                if (idList.size() > 0) {
                    pushHistoryService.updateStatus(idList, 1);
                }
            }
            return Msg.success().add("list", list);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Msg.fail().add("error", e);
        }
    }

    /**
     * 查询推送历史列表
     */
    @GetMapping("/selectById")
    public Msg selectById(Long id) {
        PushHistory pushHistory = pushHistoryService.selectPushHistoryById(id);
        PushHistory pushHistoryToUpdate = new PushHistory();
        pushHistoryToUpdate.setId(pushHistory.getId());
        pushHistoryToUpdate.setStatus((long) 2);
        pushHistoryService.updatePushHistory(pushHistoryToUpdate);
        return Msg.success().add("pushHistory", pushHistory);
    }
}
